using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using iTextSharp.text;

namespace PocoReport
{
    public class Content: IPart
    {
        private static readonly Regex FieldRegEx = new Regex("\\{([\\w\\.]+)(:([^}]+))?\\}", RegexOptions.Compiled);
        public string Value { get; set; }

        public Content()
        {            
        }

        public Content(string value)
        {
            Value = value;
        }

        public IElement GetPdfElement(Document document, Style parentStyle, Scope scope)
        {
            string output = FieldRegEx.Replace(Value, new MatchEvaluator(scope.FieldEvaluator));
            Chunk chunk = new Chunk(output)
                              {
                                  Font = GetPdfFont(parentStyle)
                              };
            string property = parentStyle.Properties["page-break-after"];
            if(property != null && property == "true")
            {
                EmptyElement element = new EmptyElement();
                element.Add(chunk);
                element.Add(new PageBreakElement());
                return element;
            }
            return chunk;
        }

        public virtual Font GetPdfFont(Style style)
        {
            System.Drawing.Font font = TextStyle.GetFont(style);
            Font textFont = FontFactory.GetFont(font.Name, font.Size);

            int pdfStyle = 0;
            if (font.Bold) pdfStyle |= 1;
            if (font.Italic) pdfStyle |= 2;
            if (font.Underline) pdfStyle |= 4;
            if (font.Strikeout) pdfStyle |= 8;
            textFont.SetStyle(pdfStyle);

            return textFont;
        }


        public void Load(XNode node)
        {
            Value = node.ToString();
        }

        public XNode Save()
        {
            return new XText(Value);
        }
    }
}